package com.myres.dao;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Transactional;

import com.myres.model.Category;

public class CategoryDao extends HibernateDaoSupport{
	public CategoryDao(){
		super();
		System.out.println("constructor of CategoryDao");
	}
	public void delete(Category category){
		getHibernateTemplate().delete(category);
	}

	public void delete(int id) {
		delete(get(id));
	}
	
	public List<Category> findAll() {
		String hql = "from Category";
		return (List<Category>)getHibernateTemplate().find(hql);
	}
	
	public List<Category> findAllInRange(Integer startWith,Integer size){
		String hql = "from Category";
		return getCategoriesInRangeWithHql(startWith,size,hql);
	}

	/**
	 * 
	 * @param startWith keep null if you don't want to use in range function.
	 * @param size same as above.
	 * @return
	 */
	public List<Category> findAllOrderByPriorityInRange(Integer startWith,Integer size){
		String hql = "from Category c order by c.priority";
		if(startWith==null||size==null){
			return getHibernateTemplate().find(hql);
		}
		return getCategoriesInRangeWithHql(startWith,size,hql);
	}

	public List<Category> findByName(String name){
		String hql = "from Category c where c.name="+"'"+name+"'";
		return (List<Category>)getHibernateTemplate().find(hql);
	}
	
	/**
	 * 
	 * @param name
	 * @param startWith keep null if you don't want to use in range function.
	 * @param size same as above.
	 * @return
	 */
	public List<Category> findByNameOrderByPriorityInRange(String name,Integer startWith,Integer size){
		String hql = "from Category c where c.name="+"'"+name+"' order by c.priority";
		if(startWith==null||size==null){
			return getHibernateTemplate().find(hql);
		}
		return (List<Category>)getHibernateTemplate().find(hql);
	}
	
	public Category get(int id){
		return getHibernateTemplate().get(Category.class, id);
	}
	
	private List<Category> getCategoriesInRangeWithHql(final Integer startWith,final Integer size,final String hql){
		List<Category> resultList = getHibernateTemplate().executeFind(new HibernateCallback(){
					public Object doInHibernate(Session session)
							throws HibernateException, SQLException {
				List<Category> result = session.createQuery(hql).setFirstResult(startWith)
						.setMaxResults(size).list();
				return result;
			}
			
		});
		return resultList;
	}
	
	
	
	public int save(Category category){
		getHibernateTemplate().save(category);
		return category.getId();
	}
	
	
	public int saveOrUpdate(Category category){
		getHibernateTemplate().saveOrUpdate(category);
		return category.getId();
	}
	
	public void update(Category category){
		getHibernateTemplate().update(category);
	}
	
}
